﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Windows.Forms;


namespace ArcEngine.Editor
{

	/// <summary>
	/// Configuration class
	/// </summary>
	static class Config
	{
		/// <summary>
		/// Load configuration from file
		/// </summary>
		/// <returns></returns>
		public static bool Load()
		{
			// File exists ??
			if (File.Exists(confFileName) == false)
				return false;


			// Parse the xml file 
			XmlDocument doc = new XmlDocument();

			try
			{
				doc.Load(confFileName);


				// Checks the header
				XmlElement xml = doc.DocumentElement;
				if (xml.Name.ToLower() != "editor")
					return false;



				XmlNodeList nodes = xml.ChildNodes;
				foreach (XmlNode node in nodes)
				{
					if (node.NodeType == XmlNodeType.Comment)
						continue;


					switch (node.Name.ToLower())
					{
						case "levelrefreshrate":
						{
							LevelRefreshRate = int.Parse(node.Attributes["value"].Value);
						}
						break;

					}
				}
			}
			catch (Exception)
			{
				MessageBox.Show("Error in configuration file !", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return false;
			}




			return true;
		}


		/// <summary>
		/// Save configuration to file
		/// </summary>
		/// <returns></returns>
		public static bool Save()
		{
			XmlWriterSettings settings = new XmlWriterSettings();
			settings.Indent = true;
			settings.OmitXmlDeclaration = false;
			settings.IndentChars = "\t";
			settings.Encoding = ASCIIEncoding.UTF8;

			XmlWriter xml = XmlWriter.Create(confFileName, settings);
			xml.WriteStartDocument(true);
			xml.WriteStartElement("editor");

			xml.WriteStartElement("levelrefreshrate");
			xml.WriteAttributeString("value", LevelRefreshRate.ToString());
			xml.WriteEndElement();


			xml.WriteEndElement();
			xml.WriteEndDocument();

			xml.Close();
			
			return true;
		}





		#region Properties




		/// <summary>
		/// Configuration filename
		/// </summary>
		static public string ConfFileName
		{
			get
			{
				return confFileName;
			}

			set
			{
				confFileName = value;
				if (string.IsNullOrEmpty(confFileName))
					ConfFileName = "config.xml";
			}
		}
		static string confFileName = "conf.xml";



		/// <summary>
		/// Level refresh rate
		/// </summary>
		static public int LevelRefreshRate = 100;

		#endregion

	}

}
